package com.studio5704website.infrastructure.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author Gao
 * AES加密工具类配置
 */
@Configuration
public class AESConfig {
    private static final String algorithm = "AES";

    private static final String transformation  = "AES/CBC/PKCS5Padding";

    @Bean(name = "encryptCipher")
    public Cipher encryptCipher(@Value("${aes.key}") String key) throws Exception {
        Cipher cipher = Cipher.getInstance(transformation);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        return cipher;
    }

    @Bean(name = "decryptCipher")
    public Cipher decryptCipher(@Value("${aes.key}") String key) throws Exception {
        Cipher cipher = Cipher.getInstance(transformation);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
        return cipher;
    }
}
